/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.manager.controler;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.asiainfo.ability.base.utils.JsonUtils;
import org.asiainfo.ability.base.utils.Response;
import org.asiainfo.ability.gateway.cache.CacheService;
import org.asiainfo.ability.gateway.code.OnOffState;
import org.asiainfo.ability.gateway.dao.AbilityDao;
import org.asiainfo.ability.gateway.dao.ClientDao;
import org.asiainfo.ability.gateway.model.Ability;
import org.asiainfo.ability.gateway.vo.Token;
import org.asiainfo.ability.gateway.vo.TokenResp;
import org.asiainfo.ability.manager.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: visen
 * @Date: 2018/1/16
 * @Description:
 */
@RestController
public class AbilityControler {
    public static final Logger logger = LogManager.getLogger(AbilityControler.class);

    @PostConstruct
    public void init() {
    }

    @Autowired
    private AdminService adminService;


    @Autowired
    private AbilityDao abilityDao;
    @Autowired(required = false)
    private ClientDao clientDao;

    @RequestMapping(value = "/admin/ability", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public @ResponseBody
    String listAbility(HttpServletRequest request, HttpServletResponse response) {
        List<Ability> abilities = abilityDao.listAbilitySummaries();
        Map ret = new HashMap<>();
        ret.put("data", abilities);
        ret.put("code", 0);
        ret.put("msg", "");
        ret.put("count", abilities.size());
        return JsonUtils.toJSON(ret);
    }

    @RequestMapping(value = "/admin/ability", method = RequestMethod.POST)
    public @ResponseBody
    String createAbility(@RequestBody Ability ability, HttpServletRequest request
            , HttpServletResponse response) {
        ability.setId(String.valueOf(System.currentTimeMillis()));
        ability.setUpdateDate(new Date());
        try {
            abilityDao.createAbility(ability);
        } catch (Exception e) {
            logger.error(null, e);
            return Response.error("0", null);
        }
        return Response.success(ability.getId());
    }

    @RequestMapping(value = "/admin/ability/{id}", method = RequestMethod.DELETE)
    public @ResponseBody
    String deleteAbility(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        abilityDao.deleteAbility(Long.parseLong(id));
        ArrayList<Ability> abilitiesCache = adminService.get(CacheService.CACHE_ABILITIES, ArrayList.class, id);
        Ability abilityCache;
        for (int i = 0, len = abilitiesCache.size(); i < len; i++) {
            abilityCache = abilitiesCache.get(i);
            if(id.equals(abilityCache.getId())) {
                abilitiesCache.remove(i);
                adminService.refresh(CacheService.CACHE_ABILITIES, abilitiesCache, "");
                break;
            }
        }
        adminService.remove(CacheService.CACHE_ABILITYINFO, id);
        return null;
    }

    @RequestMapping(value = "/admin/ability/{id}", method = RequestMethod.PUT)
    public @ResponseBody
    String updateAbility(@PathVariable String id, @RequestBody Ability ability, HttpServletRequest request
            , HttpServletResponse response) {
        ability.setUpdateDate(new Date());
        ability.setId(id);
        try {
            abilityDao.updateAbility(ability);

            ArrayList<Ability> abilitiesCache = adminService.get(CacheService.CACHE_ABILITIES, ArrayList.class, "");
            if(abilitiesCache != null) {
                Ability abilityCache;
                for (int i = 0, len = abilitiesCache.size(); i < len; i++) {
                    abilityCache = abilitiesCache.get(i);
                    if(id.equals(abilityCache.getId())) {
                        abilitiesCache.remove(i);
                        if(ability.getState() == OnOffState.on) {
                            abilitiesCache.add(ability);
                        }
                        adminService.refresh(CacheService.CACHE_ABILITIES, abilitiesCache, "");
                        break;
                    }
                }
            }
            adminService.refresh(CacheService.CACHE_ABILITYINFO, ability, id);

        } catch (Exception e) {
            logger.error(null, e);
            return Response.error("0", null);
        }

        return Response.success();
    }


    @RequestMapping(value = "/admin/ability/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public @ResponseBody
    String getAbility(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        Ability ability = abilityDao.loadAbility(Long.parseLong(id));
        if (ability != null) {
            return JsonUtils.toJSON(ability);
        }
        return null;

    }




    public static void main(String[] args) {
        Token token = new Token();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, 12);
        token.setExpireTime(calendar.getTime());
        TokenResp resp = new TokenResp();
        resp.setToken(UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
        resp.setExpireTime(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(token.getExpireTime()));
        System.out.println(JsonUtils.toJSON(resp));
        //yyyyMMddHHmmssSSS
        //AbilityApplicationContext.putToken(clientId, token);
    }
}
